/*
Copyright (c) 2009, Heinrich C. Spreiter
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  - Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
  
  - Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
  
  - Neither the name of the author nor the names of its contributors may be used
  to endorse or promote products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
  KohYaoNoi.g
  @version 0.1 04.12.2009
  @author HSP spreiter301@gmail.com
  
  Defines the grammar for Koh Yao Noi
*/
grammar KohYaoNoi;

options {
  language=Java;
  output=AST;
  backtrack=true;
  memoize=true;
  ASTLabelType=KynTree;
}

tokens {
  PBODY;
  PROPERTY;
  WBODY;
  WIDGET;
  BOOL;
  VARACC;
  METACC;
  ARGLIST;
}

@header {
package ch.kynlang.compiler;
import ch.kynlang.compiler.tree.*;
import ch.kynlang.compiler.symbol.*;
}
@lexer::header {
package ch.kynlang.compiler;
import ch.kynlang.compiler.tree.*;
import ch.kynlang.compiler.symbol.*;
}

@members {
private SymbolTable st = null;
public KohYaoNoiParser(TokenStream input, SymbolTable st) {
  super(input);
  this.st = st;
}

public void displayRecognitionError(String[] tokenNames,
                                        RecognitionException re) {
    KynTree kt = new KynTree(re.token);
    
    KohYaoNoiError err = new KohYaoNoiError(kt, super.getErrorMessage(re, tokenNames));
    st.error(err);
    //super.displayRecognitionError(tokenNames, re);
}
}
//-------------------- Parser
program                 : packageDef?
                            importDef*
                            (macroDef | varDef)*
                            widget
                        ;

packageDef              : PACKAGE^ qualifiedName SEMI!
                        ;
            
importDef               : IMPORT qualifiedName AS IDENTIFIER SEMI -> ^(AS IDENTIFIER qualifiedName)
                        | IMPORT^ qualifiedName SEMI!
                        ;
            
varDef                  : DEF^ IDENTIFIER EQ! value SEMI!
                        ;
            
macroDef                : HASH^ IDENTIFIER propertyBody // setup macrolookup table
                        ;
                        // no rewrite to ^(PROPERTY ..) we just loop over each property
                        // and define it in the component like the normal property
macroAccess             : HASH^ IDENTIFIER
                        ;
            
propertyBody            : LPAREN ( property COMMA? )* RPAREN -> ^(PBODY property*)
                        ;
            
property                : IDENTIFIER COLON value -> ^(PROPERTY IDENTIFIER value)
                        | macroAccess
                        ;
            
widget                  : wtype=IDENTIFIER wname=IDENTIFIER propertyBody widgetBody? -> ^(WIDGET $wtype $wname propertyBody widgetBody?)
                        ;

widgetBody              : LBRACE widget* RBRACE -> ^(WBODY widget*)
                        ;

value                   : literal
                        | newObject
                        | variableAccess
                        ;

newObject               : NEW^ IDENTIFIER LPAREN! argList? RPAREN!
                        ;

variableOrMethodAccess  : variableAccess
                        | methodAccess
                        ;
            
variableAccess          : IDENTIFIER ( DOT variableOrMethodAccess )? -> ^(VARACC IDENTIFIER variableOrMethodAccess?)
                        ;
            
methodAccess            : IDENTIFIER LPAREN argList? RPAREN
                            ( DOT variableOrMethodAccess)? -> ^(METACC IDENTIFIER argList? variableOrMethodAccess?)
                        ;
            
argList                 : value ( COMMA value )* -> ^(ARGLIST value+)
                        ;
            
qualifiedName           : IDENTIFIER ( DOT IDENTIFIER )* -> IDENTIFIER+
                        ;
            
booleanLiteral          : TRUE
                        | FALSE
                        ;
            
literal                 : INTEGER
                        | FLOAT
                        | STRINGLITERAL
                        | CHARACTERLITERAL
                        | booleanLiteral -> ^(BOOL booleanLiteral)
              //          | NULL
                        ;
                        
//-------------------- Lexer
PACKAGE           : 'package';
IMPORT            : 'import';
AS                : 'as';
DEF               : 'def';
FLOAT             : ('0' .. '9')+ '.' ('0' .. '9')+('f'|'F')?;
INTEGER           : ('0' | '1' .. '9' ('0' .. '9')*)('l'|'L')?;
TRUE              : 'true';
FALSE             : 'false';
//NULL              : 'null';
NEW               : 'new';
CHARACTERLITERAL  : '\'' ( EscapeSequence | ~('\''|'\\') ) '\'';
STRINGLITERAL     : '"' ( ~('\\'|'"') | EscapeSequence )* '"';
IDENTIFIER        : Letter (Letter|JavaIDDigit)*;
LPAREN            : '(';
RPAREN            : ')';
LBRACE            : '{';
RBRACE            : '}'; 
LBRACKET          : '[';
RBRACKET          : ']';
SEMI              : ';';
COLON             : ':';
COMMA             : ',';
DOT               : '.';
HASH              : '#';
EQ                : '=';

//-------------------- Fragments
fragment
EscapeSequence : ('\\b'|'\\t'|'\\n'|'\\f'|'\\r'|'\\"'|'\\\\');


// copied from Terence Parr's Java 1.5 grammar http://www.antlr.org/grammar/1152141644268/Java.g
fragment
Letter
    :  '\u0024' |
       '\u0041'..'\u005a' |
       '\u005f' |
       '\u0061'..'\u007a' |
       '\u00c0'..'\u00d6' |
       '\u00d8'..'\u00f6' |
       '\u00f8'..'\u00ff' |
       '\u0100'..'\u1fff' |
       '\u3040'..'\u318f' |
       '\u3300'..'\u337f' |
       '\u3400'..'\u3d2d' |
       '\u4e00'..'\u9fff' |
       '\uf900'..'\ufaff'
    ;

// copied from Terence Parr's Java 1.5 grammar http://www.antlr.org/grammar/1152141644268/Java.g
fragment
JavaIDDigit
    :  '\u0030'..'\u0039' |
       '\u0660'..'\u0669' |
       '\u06f0'..'\u06f9' |
       '\u0966'..'\u096f' |
       '\u09e6'..'\u09ef' |
       '\u0a66'..'\u0a6f' |
       '\u0ae6'..'\u0aef' |
       '\u0b66'..'\u0b6f' |
       '\u0be7'..'\u0bef' |
       '\u0c66'..'\u0c6f' |
       '\u0ce6'..'\u0cef' |
       '\u0d66'..'\u0d6f' |
       '\u0e50'..'\u0e59' |
       '\u0ed0'..'\u0ed9' |
       '\u1040'..'\u1049'
   ;
   
//-------------------- whitespace and comments
WS  :  (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;}
    ;

COMMENT
    :   '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;}
    ;

LINE_COMMENT
    : '//' ~('\n'|'\r')* '\r'? '\n' {$channel=HIDDEN;}
    ;